<template>
  <div class="comments-from-box page">
    <van-nav-bar title="发表评价" class="bg_grey" left-arrow @click-left="$router.go(-1)" />
    <div class="top-tis">说说宝贝的使用体验
      <span class="save" @click="submit">保存</span>
    </div>
    <div class="content">
      <div class="from">
        <div class="product-box">
          <div class="product-info" v-for="(item,index) in goodsList" :key="index">
            <div class="imgPath">
              <van-image :width="$tools.toPX(100)" :height="$tools.toPX(100)" fit="contain" class="img" lazy-load :src="item.goods_img">
                <template v-slot:loading>
                  <van-loading type="spinner" size="24" />
                </template>
              </van-image>
            </div>
            <div class="detail">
              <div class="name van-ellipsis">{{item.goods_name}}</div>
              <div class="spec">{{item.goods_spec_names}}</div>
            </div>
          </div>
          <div class="rate" v-if="!appraiseId">
            <span class="label">描述相符</span>
            <van-rate v-model="apply.goodsScore" size="24" icon="rate-red" void-icon="rate-gray" />
          </div>
          <div class="textarea">
            <van-field class="message" v-model="apply.content" rows="5" autosize type="textarea" placeholder="请输入你的评价" />
          </div>
          <div class="upload">
            <template v-if="isApp">
              <div class="images">
                <template v-if="apply.images.length">
                  <img v-for="(item,i) in apply.images" :key="i" :src="item.url" @click.stop="showIMG()" v-if="apply.images.length" />
                </template>
                <span class="van-icon van-icon-photograph van-uploader__upload-icon photograph" @click="openAction()"
                  v-if="apply.images.length==0"></span>
              </div>
              <span class="van-ico-n van-icon-clear van-uploader__preview-delete " v-if="apply.images.length " @click="removeImg() "></span>
            </template>
            <template v-else>
              <div class="images ">
                <van-uploader class="uploader " name="images " v-model="apply.images " :after-read="afterRead "
                  :max-count="9 " />
              </div>
            </template>
            <div class="loading " v-if="isFrontLoading ">
              <van-loading size="24px " color="#ffffff "></van-loading>
            </div>
          </div>
        </div>
      </div>
    </div>
    <van-image-preview v-model="showPreview " closeable :showIndex="false " :class="{isApp:isApp} " v-if="isApp "
      :images="images " />
    <van-action-sheet v-model="isAction " :round="false " @select="selectAction " cancel-text="取消 " :actions="actions "
      description="上传反馈图片 " />
  </div>
</template>
<script>
import mixins from '@/utils/mixins';
export default {
  name: 'commentsFrom',
  data() {
    return {
      showPreview: false,
      images: [],
      apply: {
        images: [],
        content: '',
        goodsScore: 0
      },
      isFrontLoading: false,
      orderInfo: {},
      goodsList: [],
      imgType: '', // 区分打开的是相机还是相册
      actions: [{ name: '拍照' }, { name: '相册' }],
      isAction: false,
      appraiseId: null // 评价ID 有评价ID表示追评
    };
  },
  mixins: [mixins],
  computed: {
    isApp: {
      get() {
        return !!localStorage.getItem('isApp') || !!this.$route.query.isApp;
      }
    }
  },
  created() {},
  mounted() {
    this.getOrderDetail();
    if (this.$route.query.appraiseId) this.appraiseId = this.$route.query.appraiseId;
  },
  methods: {
    afterRead(data, detail) {
      var fileFormData = new FormData();
      var FiletypeName = null;
      var fileData = null;
      if (!this.isApp) {
        FiletypeName = data.content.replace(/data:image\/([^;]+).*/i, '$1');
      } else {
        fileData = 'data:image/' + detail + ';base64,' + data;
      }
      fileFormData.append('fileType', !this.isApp ? FiletypeName : detail);
      fileFormData.append('base64', !this.isApp ? data.content : fileData);
      this.$set(this, 'isFrontLoading', true); // loading加载
      // 非APP用web上传
      if (!this.isApp) {
        this.fileUploadAccountImg(fileFormData, detail.name);
      } else {
        return fileFormData;
      }
    },
    getOrderDetail() {
      const options = { id: this.$route.query.id };
      // const options = { id: 11 };
      this.$API.user.order(options, 'detail').then(res => {
        if (!res.code) {
          this.orderInfo = res.data.orderObj;
          this.goodsList = res.data.goodsList;
        } else {
          this.$toast('获取失败');
        }
      });
    },
    // 显示图片
    showIMG() {
      this.images = this.apply.images;
      this.showPreview = true;
    },
    removeImg() {
      this.$set(this.apply, 'images', []);
    },
    // 上传评价图集
    fileUploadAccountImg(fileFormData, type) {
      this.$API.global.cardFileUpload(fileFormData).then(res => {
        if (!res.data.code) {
          var _res = res.data;
          if (!this.isApp) {
          }
          this.apply.images.push({
            url: _res.src
          });
          this.apply.images = this.apply.images.filter(item => item.url);
          this.isFrontLoading = false;
        } else {
          this.$toast(res.data.message);
          this.isFrontLoading = false;
        }
      });
    },
    // 文件流转base64
    toBase64(data, callbark) {
      var trans = window.api.require('trans');
      trans.decodeImgToBase64(
        {
          imgPath: 'widget://' + data
        },
        (ret, err) => {
          if (ret.status) {
            callbark && callbark(ret.base64Str.replace(/[\r\n]/g, ''));
          } else {
            console(JSON.stringify(err));
          }
        }
      );
    },
    getPicture(type) {
      window.api.getPicture(
        {
          sourceType: type === 'camera' ? 'camera' : 'album', // 从相册中选择
          encodingType: 'jpg',
          mediaValue: 'pic',
          allowEdit: false,
          destinationType: 'base64', // 返回base64地址
          quality: 70,
          saveToPhotoAlbum: true
        },
        (ret, err) => {
          this.isAction = false;
          var fileType = ret.base64Data.replace(/data:image\/([^;]+).*/i, '$1');
          var base64Data = ret.base64Data.replace(/^data:image\/\w+;base64,/, '');
          var fileFormData = this.afterRead(base64Data, fileType);
          this.fileUploadAccountImg(fileFormData, this.imgType);
        }
      );
    },
    // 打开系统相册
    UIMediaScanner() {
      var UIAlbumBrowser = window.api.require('UIAlbumBrowser');
      UIAlbumBrowser.imagePicker(
        {
          max: 1,
          showCamera: false,
          styles: {
            bg: '#fff',
            mark: {
              icon: '',
              position: 'bottom_left',
              size: 20
            },
            nav: {
              bg: 'rgba(0,0,0,0.6)',
              titleColor: '#fff',
              titleSize: 18,
              cancelColor: '#fff',
              cancelSize: 16,
              finishColor: '#fff',
              finishSize: 16
            }
          },
          rotation: true
        },
        ret => {
          if (ret) {
            this.isAction = false;
            if (ret.eventType === 'nextStep') {
              var list = ret.list[0];
              this.toBase64(list.path, base64Str => {
                var fileFormData = this.afterRead(base64Str, list.suffix);
                this.fileUploadAccountImg(fileFormData, this.imgType);
              });
              UIAlbumBrowser.closePicker();
            }
          }
        }
      );
    },
    selectAction(action, index) {
      if (!index) {
        this.getPicture('camera');
      } else {
        this.UIMediaScanner();
      }
    },
    openAction() {
      this.isAction = true;
    },
    // 发表评价
    submit() {
      if (!this.appraiseId && this.apply.goodsScore === 0) {
        this.$toast('请打分');
        return;
      }
      if (!this.apply.content) {
        this.$toast('请输入评价内容');
        return;
      }
      if (this.apply.images.length === 0) {
        this.$toast('请上传评价图片');
        return;
      }
      let urls = [];
      this.apply.images.forEach(item => {
        urls.push(item.url);
      });
      let params = {
        content: this.apply.content,
        images: urls.join(',')
      };
      this.$toast.loading({ duration: 0 });
      this.$dialog.confirm({
        title: '温馨提醒',
        message: '确认提交该评价吗？',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, done) => {
          if (action === 'confirm') {
            setTimeout(() => {
              if (!this.appraiseId) {
                params.id = this.$route.query.id; // 订单详情ID
                params.goodsScore = this.apply.goodsScore;
                this.submitComments(params, done());
              } else {
                params.id = this.appraiseId; // 评价ID
                this.appendComments(params, done());
              }
            }, 1000);
          } else {
            done();
          }
        }
      });
    },
    // 发表评价
    submitComments(params, callback) {
      this.$API.comments.submitComments(params).then(res => {
        this.$toast(!res.code ? '评价成功' : res.message);
        this.$router.go(-1);
        callback();
      });
    },
    // 追评
    appendComments(params, callback) {
      this.$API.comments.appendComments(params).then(res => {
        this.$toast(!res.code ? '评价成功' : res.message);
        this.$router.go(-1);
        callback();
      });
    }
  }
};
</script>
<style lang="less" scoped>
.comments-from-box {
  display: flex;
  flex-direction: column;
  .top-tis {
    padding: 10px 20px 20px;
    font-size: 28px;
    color: #353535;
    position: relative;
    .save {
      color: #ff0034;
      font-size: 28px;
      position: absolute;
      top: -65px;
      right: 30px;
      z-index: 999;
    }
  }
  .content {
    flex: 1;
    overflow: auto;
    .product-box {
      padding: 5px 20px 0;
      .rate {
        padding: 10px 0;
        display: flex;
        align-items: center;
        .label {
          font-size: 28px;
          color: #666;
          margin-right: 10px;
        }
      }
      .textarea {
        padding: 20px 0;
        .message {
          padding: 20px;
          background-color: #fafafa;
          border-radius: 10px;
          .van-field__control {
            font-size: 30px;
          }
        }
      }
    }
    .upload {
      padding: 0 0 20px;
      .images {
        // width: 166px;
        min-height: 166px;
        position: relative;
        box-sizing: border-box;
        // background-color: #f7f8fa;
        border-radius: 8px;
        .photograph {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }
}
</style>
